<template>
  <page-header-wrapper>
    <a-card :bordered="false">
      <!-- 查询栏 -->
      <div class="table-page-search-wrapper">
        <a-form
          layout="inline">
          <a-row :gutter="48">
            <a-col :md="8" :sm="24">
              <a-form-item label="应用ID" name="id" :rules="[{ required: true, message: '请输入应用ID' }]">
                <a-input v-model="queryParam.id" placeholder="请输入" />
              </a-form-item>
            </a-col>
            <!-- <a-col :md="8" :sm="24">
              <a-form-item label="应用名称" name="id" :rules="[{ required: true, message: '请输入应用名称' }]">
                <a-input v-model="queryParam.name" placeholder="请输入" />
              </a-form-item>
            </a-col> -->
            <a-col :md="8" :sm="24">
              <a-form-item label="状态">
                <a-select v-model="queryParam.status" placeholder="请选择" default-value="0">
                  <a-select-option value="0">全部</a-select-option>
                  <a-select-option value="1">启用</a-select-option>
                  <a-select-option value="2">禁用</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <span class="table-page-search-submitButtons">
                <a-button
                  type="primary"
                  html-type="submit"
                  @click.stop.prevent="handleSearch()"
                >查询</a-button>
                <a-button style="margin-left: 8px" @click="() => this.queryParam = {}">重置</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>

      <!-- 操作栏 -->
      <div class="table-operator">
        <a-button type="primary" icon="plus" @click="handleAdd">新建</a-button>
      </div>

      <!-- 用户列表 -->
      <s-table
        size="default"
        ref="table"
        row-key="id"
        :columns="columns"
        :data="loadData"
        :loading="loading"
        :alert="alert"
        :show-pagination="true"
        :scroll="{ x: true }"
        :indent-size="5"
      >

        <span slot="serial" slot-scope="text, record, index">{{ index + 1 }}</span>
        <span slot="status" slot-scope="text">
          <a-badge :status="text | statusTypeFilter" :text="text | statusFilter" />
        </span>
        <span slot="createTime" slot-scope="text">{{ text | moment }}</span>
        <span slot="description" slot-scope="text">
          <ellipsis :length="4" tooltip>{{ text }}</ellipsis>
        </span>

        <span slot="action" slot-scope="text, record">
          <template>
            <a @click="handleEdit(record)">编辑</a>
            <a-divider type="vertical" />
            <a @click="handleAssignRole(record)">应用配置</a>
            <a-divider type="vertical" />
            <a @click="handleChangeStatus(record)">{{ record.status === 1 ? '禁用' : '启用' }}</a>
            <a-divider type="vertical" />
            <a @click="handleDelete(record)">删除</a>
          </template>
        </span>
      </s-table>

      <!-- 添加应用 -->
      <a-modal
        title="添加应用"
        style="top: 20px;"
        :width="800"
        v-model="addVisible"
        @ok="handleOk($event, 'add')"
      >
        <a-form class="permission-form" :form="form">

          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            label="应用名称"
            hasFeedback
          >
            <a-input
              placeholder="应用名称"
              v-decorator="['name', {rules: [{ required: true, message: '请输入应用名称' }], validateTrigger: ['change', 'blur']}]"
            />
          </a-form-item>

          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            label="appKey"
            hasFeedback
          >
            <a-input
              placeholder="appKey"
              v-decorator="['appKey', {rules: [{ required: true, message: '请输入appKey' }], validateTrigger: ['change', 'blur']}]"
            />
          </a-form-item>

          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            label="appSecret"
            hasFeedback
          >
            <a-input
              placeholder="请输入appSecret"
              v-decorator="['appSecret', {rules: [{ required: true, message: '请输入appSecret' }], validateTrigger: ['change', 'blur']}]"
            />
          </a-form-item>

          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            label="状态"
            hasFeedback
          >
            <a-select v-decorator="['status', { initialValue: 1 }]">
              <a-select-option :value="1">正常</a-select-option>
              <a-select-option :value="2">禁用</a-select-option>
            </a-select>
          </a-form-item>

        </a-form>
      </a-modal>

      <!-- 编辑用户 -->
      <a-modal
        title="操作"
        style="top: 20px;"
        :width="800"
        v-model="visible"
        @ok="handleOk($event,'edit')"
      >
        <a-form class="permission-form" :form="form">
          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            label="应用ID"
            hasFeedback
            validateStatus="success"
            hidden="hidden"
          >
            <a-input
              placeholder="ID"
              disabled="disabled"
              v-decorator="['id']"
            />
          </a-form-item>

          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            label="应用名称"
            hasFeedback
            validateStatus="success"
          >
            <a-input
              placeholder="应用名称"
              v-decorator="['name']"
            />
          </a-form-item>

          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            label="appKey"
            hasFeedback
            validateStatus="success"
          >
            <a-input
              placeholder="appKey"
              v-decorator="['appKey']"
            />
          </a-form-item>

          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            label="appSecret"
            hasFeedback
            validateStatus="success"
          >
            <a-input
              placeholder="appSecret"
              v-decorator="['appSecret']"
            />
          </a-form-item>

          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            label="状态"
            hasFeedback
          >
            <a-select v-decorator="['status', { initialValue: 1 }]">
              <a-select-option :value="1">正常</a-select-option>
              <a-select-option :value="2">禁用</a-select-option>
            </a-select>
          </a-form-item>
        </a-form>
      </a-modal>

      <!-- 应用配置 -->
      <a-modal
        title="应用配置"
        style="top: 20px;"
        :width="800"
        v-model="roleVisible"
        @ok="handleOk($event,'role')"
      >
        <a-form class="permission-form" :form="form">
          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            label="ID"
            hidden="hidden"
          >
            <a-input
              placeholder="ID"
              disabled="disabled"
              v-decorator="['id']"
            />
          </a-form-item>
          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            label="当前用户"
          >
            <a-input
              :disabled="true"
              placeholder="用户名"
              v-decorator="['username']"
            />
          </a-form-item>
          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            label="应用配置"
          >
            <a-transfer
              ref="transfer"
              :row-key="item => item.id"
              :target-keys="selectedRoles"
              :data-source="allRoles"
              :titles="['应用列表', '已有应用']"
              :render="item => item.name"
              @change="handleRoleChange"
            />
          </a-form-item>
        </a-form>
      </a-modal>
    </a-card>
  </page-header-wrapper>
</template>

<!--suppress JSUnresolvedVariable -->
<script>
import pick from 'lodash.pick'
import { PERMISSION_ENUM } from '@/core/permission/permission'
import {
  assignRole,
  getUserRoleListById
} from '@/api/base'
import { getAppList, createApp, updateApp, deleteApp, getAppById } from '@/api/application'
import { labelCol, statusMap, wrapperCol } from '@/utils/constant'

const columns = [
  {
    title: '应用ID',
    width: 200,
    fixed: 'left',
    dataIndex: 'id'
  },
  {
    title: '应用名称',
    width: 100,
    dataIndex: 'name'
  },
  {
    title: 'appKey',
    width: 200,
    dataIndex: 'appKey'
  },
  {
    title: 'appSecret',
    width: 200,
    dataIndex: 'appSecret'
  },
  {
    title: '状态',
    width: 100,
    dataIndex: 'status',
    scopedSlots: { customRender: 'status' }
  },
  {
    title: '创建时间',
    width: 200,
    dataIndex: 'createdAt',
    scopedSlots: { customRender: 'createTime' },
    sorter: true
  },
  {
    title: '操作',
    width: 230,
    dataIndex: 'action',
    fixed: 'right',
    scopedSlots: { customRender: 'action' }
  }
]

export default {
  name: 'TableList',
  data () {
    return {
      description: '列表使用场景：后台管理中的权限管理以及应用管理，可用于基于 RBAC 设计的应用权限控制，颗粒度细到每一个操作类型。',

      visible: false,
      addVisible: false,
      pwdVisible: false,
      roleVisible: false,

      loading: false,
      alert: true,

      state: {
        time: 60,
        level: 0,
        smsSendBtn: false,
        passwordLevel: 0,
        passwordLevelChecked: false,
        percent: 10,
        progressColor: '#FF0000'
      },

      labelCol: labelCol,
      wrapperCol: wrapperCol,
      form: this.$form.createForm(this),
      permissions: [],

      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {},
      // 表头
      columns,
      loadData: (parameter) => {
        const finalParameters = Object.assign(parameter, this.queryParam)
        console.log(finalParameters)
        if (finalParameters.id) {
          return getAppById(parameter)
          .then(res => {
            return res.data
          })
        } else {
          return getAppList(finalParameters)
          .then(res => {
            console.log(res.data)
            return res.data
          })
        }
      },

      expandedRowKeys: [],
      selectedRowKeys: [],
      selectedRows: [],

      selectedRoles: [],
      allRoles: []
    }
  },
  filters: {
    statusFilter (key) {
      return statusMap[key].text
    },
    statusTypeFilter (type) {
      return statusMap[type].status
    },
    permissionFilter (key) {
      const permission = PERMISSION_ENUM[key]
      return permission && permission.label
    }
  },
  methods: {
    doAdd (values) {
      createApp({
        name: values.name,
        appKey: values.appKey,
        appSecret: values.appSecret,
        status: values.status
      }).then(response => {
        if (response.code === 0) {
          this.$notification['success']({ message: '成功', description: '添加成功', duration: 4 })
          this.$refs.table.refresh()
        } else {
          this.$notification['error']({ message: '错误', description: response.msg, duration: 4 })
        }
        this.addVisible = false
      }).catch(err => {
        this.$notification['error']({ message: '错误', description: err, duration: 4 })
        this.addVisible = false
      })
    },
    doUpdate (values) {
      updateApp({
        id: values.id,
        name: values.name,
        appKey: values.appKey,
        appSecret: values.appSecret,
        status: values.status
      }).then(response => {
        if (response.code === 0) {
          this.$notification['success']({ message: '成功', description: '修改成功', duration: 4 })
          this.$refs.table.refresh()
        } else {
          this.$notification['error']({ message: '错误', description: response.msg, duration: 4 })
        }
        this.visible = false
      }).catch(err => {
        this.$notification['error']({ message: '错误', description: err, duration: 4 })
        this.visible = false
      })
    },
    doDel (record) {
      deleteApp({
        ids: [record.id]
      }).then(response => {
        if (response.code === 0) {
          this.$notification['success']({ message: '成功', description: '删除成功', duration: 4 })
          this.$refs.table.refresh()
        } else {
          this.$notification['error']({ message: '错误', description: response.msg, duration: 4 })
        }
      }).catch(err => {
        this.$notification['error']({ message: '错误', description: err, duration: 4 })
      })
    },
    doAssignRole (record) {
      assignRole({
        id: record.id,
        roleIds: this.selectedRoles
      }).then(response => {
        if (response.code === 0) {
          this.$notification['success']({ message: '成功', description: '修改成功', duration: 4 })
          this.$refs.table.refresh()
        } else {
          this.$notification['error']({ message: '错误', description: response.msg, duration: 4 })
        }
      }).catch(err => {
        this.$notification['error']({ message: '错误', description: err, duration: 4 })
      })
    },
    handleAssignRole (record) {
      this.selectedRoles = []
      this.roleVisible = true
      this.$nextTick(() => {
        this.form.setFieldsValue(pick(record, ['id', 'username']))
      })

      getAppList()
        .then(response => {
          if (response.code === 0) {
            this.allRoles = response.data
          }

          getUserRoleListById({
            id: record.id
          }).then(response => {
            if (response.code === 0) {
              this.selectedRoles = response.data
            }
          }).catch(() => {
            this.roleVisible = false
          })
        })
        .catch(() => {
          this.roleVisible = false
        })
    },
    handleRoleChange (targetKeys, direction, moveKeys) {
      this.selectedRoles = targetKeys
    },
    handleSearch () {
      this.$refs.table.refresh()
    },
    handleDelete (record) {
      const that = this
      this.$model.confirm({
        title: '确定要删除么？',
        okText: '确定',
        okType: 'danger',
        cancelText: '取消',
        onOk () {
          that.doDel(record)
        },
        onCancel () {
        }
      })
    },
    handleChangeStatus (record) {
      const that = this
      this.$model.confirm({
        title: '确定要' + (record.status === 1 ? '禁用' : '启用') + '么？',
        okText: '确定',
        okType: 'danger',
        cancelText: '取消',
        onOk () {
          record.status = record.status === 1 ? 2 : 1
          that.doUpdate(record)
        },
        onCancel () {
        }
      })
    },
    handleEdit (record) {
      this.visible = true
      console.log('record', record)

      this.$nextTick(() => {
        this.form.setFieldsValue(pick(record, ['id', 'appKey', 'appSecret', 'status', 'name']))
      })
    },
    handleOk (e, type) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        console.log(err, values)

        if (type === 'add') {
          this.doAdd(values)
        } else if (type === 'edit') {
          this.doUpdate(values)
        } else if (type === 'role') {
          this.doAssignRole(values)
        }
      })
    },
    handleAdd (record) {
      this.addVisible = true
      console.log('record', record)
      this.$nextTick(() => {
        this.form.setFieldsValue(pick(record, ['id', 'appKey', 'appSecret', 'status', 'name']))
      })
    },
    onChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    toggleAdvanced () {
      this.advanced = !this.advanced
    }
  },
  watch: {}
}
</script>

<style lang="less" scoped>
.permission-form {
  :deep(.permission-group) {
    margin-top: 0;
    margin-bottom: 0;
  }
}

</style>
